<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantid">
            <a-form-item :label="$t('门店')">
              <a-select v-model="queryParam.tenantId">
                <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                  >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('汇总时间')">
              <a-date-picker
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.bTime"
              ></a-date-picker>
              <span class="query-group-split-cust"></span>
              <a-date-picker
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.eTime"
              ></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="9" :md="10" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('仓库')">
                <a-tree-select
                  allowClear
                  v-model="queryParam.goodsStorage"
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="storeData"
                  :search-placeholder="$t('请选择')"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('选择分类')">
                <a-tree-select
                  v-model="queryParam.goodsKind"
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeData"
                  :search-placeholder="$t('请选择')"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item>
                <a-checkbox v-model="queryParam.zeroAfter">{{ $t('显示期末数量为0的商品') }}</a-checkbox>
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" @click="weekQuery">{{ $t('本周') }}</a-button>
      <a-button type="primary" @click="monthQuery">{{ $t('本月') }}</a-button>
      <a-button type="primary" @click="yearQuery">{{ $t('本年') }}</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="kind"
        class="j-table-force-nowrap"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSources"
        :pagination="false"
        :customRow="customRow"
      >
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>
      </a-table>
    </div>
    <a-row style="margin-top: 20px">
      <a-col :span="14">
        <div class="down-charts" id="myChart1"></div>
      </a-col>
      <a-col :span="10">
        <div class="down-charts" id="myChart2"></div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import { TENANT_ID } from '@/store/mutation-types'
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
let myChart1, myChart2

export default {
  name: 'GoodsKindReport',
  mixins: [JeecgListMixin],
  components: {},
  data() {
    return {
      description: '分类进销存管理页面',
      moment,
      // 表头
      columns: [
        {
          title: this.$t('分类名称'),
          align: 'left',
          dataIndex: 'kindName',
        },
        {
          title: this.$t('期初数量'),
          align: 'left',
          dataIndex: 'openNum',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('期初金额'),
          align: 'left',
          dataIndex: 'openAmount',
          customRender: (t, r) => {
            let arr = t.toString().split('.')
            if (arr.length > 1 && arr[1].length > 2) {
              return t.toFixed(2)
            }
            return t
          },
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('入库数量'),
          align: 'left',
          dataIndex: 'inNum',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('入库金额'),
          align: 'left',
          dataIndex: 'inPrice',
          customRender: (t, r) => {
            let arr = t.toString().split('.')
            if (arr.length > 1 && arr[1].length > 2) {
              return t.toFixed(2)
            }
            return t
          },
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('出库数量'),
          align: 'left',
          dataIndex: 'outNum',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('出库金额'),
          align: 'left',
          dataIndex: 'outPrice',
          customRender: (t, r) => {
            let arr = t.toString().split('.')
            if (arr.length > 1 && arr[1].length > 2) {
              return t.toFixed(2)
            }
            return t
          },
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('期末数量'),
          align: 'left',
          dataIndex: 'afterNum',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('期末金额'),
          align: 'left',
          dataIndex: 'afterAmount',
          customRender: (t, r) => {
            let arr = t.toString().split('.')
            if (arr.length > 1 && arr[1].length > 2) {
              return t.toFixed(2)
            }
            return t
          },
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
      ],
      url: {
        list: '/report/goods/goodsKindInventory/list',
      },
      dictOptions: {},
      shops: [],
      tenantid: Vue.ls.get(TENANT_ID),
      queryParam: {
        tenantId: '',
        bTime: moment().format('YYYY-MM-DD 00:00:00'),
        eTime: moment().format('YYYY-MM-DD 23:59:59'),
        goodsStorage: '',
        goodsKind: '',
        zeroAfter: true,
      },
      isCustom: true,
      treeData: [],
      storeData: [],
      dataSources: [],
    }
  },
  created() {
    if (!this.tenantid) {
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
    }
    this.initDictConfig()
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  watch: {
    dataSource(nlist) {
      this.test1(nlist)
      this.dataSources = nlist.slice()
      this.addSumRow(
        ['kindName', 'openNum', 'openAmount', 'inNum', 'inPrice', 'outNum', 'outPrice', 'afterNum', 'afterAmount'],
        this.dataSources
      )
      this.test2(this.dataSources[this.dataSources.length - 1])
    },
  },
  methods: {
    customRow(r, i) {
      return {
        style: {
          fontWeight: r.kindName == this.$t('合计') ? 700 : 400,
        },
      }
    },
    addSumRow(myArr, dataSource) {
      let that = this,
        total = {}
      myArr.forEach(function (tcn, ind) {
        if (ind == 0) {
          total[tcn] = that.$t('合计')
        } else {
          total[tcn] = 0
        }
      })
      for (let key in total) {
        dataSource.forEach(function (ds) {
          if (!isNaN(total[key])) {
            total[key] += Number(ds[key])
          }
        })
      }
      dataSource.push(total)
    },
    initDictConfig() {
      this.select()
      this.getStoreList()
      this.searchQuery()

      myChart1 = this.$echarts.init(document.getElementById('myChart1'))
      myChart2 = this.$echarts.init(document.getElementById('myChart2'), 'light')
      myChart1.showLoading({
        text: 'loading',
        color: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)',
      })
      myChart2.showLoading({
        text: 'loading',
        color: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)',
      })
    },
    getStoreList() {
      let that = this
      let storeList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      getAction('/goods/bisGoodsStore/rootList', param).then((res) => {
        if (res.success) {
          that.allChildKind = []
          storeList = res.result.records
          if (storeList.length > 0) {
            storeList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            that.storeData = that.getDataByResult(storeList)
            that.storeData.unshift({ key: '', id: '', value: '', title: this.$t('全部') })
          }
        }
      })
    },
    getHasChildStore(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      getAction('/goods/bisGoodsStore/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.storeData = [...that.storeData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    select() {
      let that = this
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      getAction('/goods/bisGoodsKind/rootList', param).then((res) => {
        if (res.success) {
          that.allChildKind = []
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            that.treeData = that.getDataByResult(res.result.records)
            that.treeData.unshift({ key: '', id: '', value: '', title: this.$t('全部') })
          } else {
            that.treeData = []
          }
        } else {
          that.$alert(res.message, this.$t('提示'), {
            confirmButtonText: this.$t('确定'),
            callback: (action) => {},
          })
        }
      })
    },
    getHasChild(record) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = record.id
      getAction('/goods/bisGoodsKind/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            record.children = that.getDataByResult(res.result.records)
            that.treeData = [...that.treeData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      let that = this
      return result.map((item) => {
        if (item.hasChild == 0 && item.key != '0') {
          that.allChildKind.push(item.key)
        }
        return item
      })
    },
    searchReset() {
      let that = this
      that.queryParam = {
        tenantId: '',
        bTime: moment().format('YYYY-MM-DD 00:00:00'),
        eTime: moment().format('YYYY-MM-DD 23:59:59'),
        goodsStorage: '',
        goodsKind: '',
        zeroAfter: true,
      }
      that.searchQuery()
    },
    weekQuery() {
      let that = this
      that.queryParam.bTime = moment().startOf('week').format('YYYY-MM-DD 00:00:00')
      that.queryParam.eTime = moment().format('YYYY-MM-DD 23:59:59')
      that.searchQuery()
    },
    monthQuery() {
      let that = this
      that.queryParam.bTime = moment().startOf('month').format('YYYY-MM-DD 00:00:00')
      that.queryParam.eTime = moment().format('YYYY-MM-DD 23:59:59')
      that.searchQuery()
    },
    yearQuery() {
      let that = this
      that.queryParam.bTime = moment().startOf('year').format('YYYY-MM-DD 00:00:00')
      that.queryParam.eTime = moment().format('YYYY-MM-DD 23:59:59')
      that.searchQuery()
    },
    test1(list) {
      let that = this
      myChart1 = that.$echarts.init(document.getElementById('myChart1'))
      myChart1.hideLoading()
      myChart1.clear()
      myChart1.setOption({
        title: {
          left: 'center',
          text: that.$t('库存数量报表'),
          show: true,
        },
        grid: {
          show: false,
          top: '40',
          bottom: '50',
          right: '20',
          left: '70',
        },
        xAxis: {
          type: 'category',
          data: that.dataBarOrLineAxios(list, 'kindName'),
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: 'left',
          },
        },
        legend: {
          itemHeight: 12,
          itemWidth: 12,
          data: [that.$t('k_入库'), that.$t('k_出库'), that.$t('k_结余')],
          icon: 'rect',
          right: 'center',
          bottom: 0,
        },
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: [
          {
            name: that.$t('k_入库'),
            data: that.dataBarOrLineAxios(list, 'inNum'),
            type: 'bar',
            barWidth: '20%',
          },
          {
            name: that.$t('k_出库'),
            data: that.dataBarOrLineAxios(list, 'outNum'),
            type: 'bar',
            barWidth: '20%',
          },
          {
            name: that.$t('k_结余'),
            data: that.dataBarOrLineAxios(list, 'afterNum'),
            type: 'bar',
            barWidth: '20%',
          },
        ],
      })
    },
    test2(info) {
      let that = this
      myChart2 = this.$echarts.init(document.getElementById('myChart2'), 'light')
      myChart2.hideLoading()
      myChart2.clear()
      let data = [
        { value: info.inNum, name: that.$t('k_入库') },
        { value: info.outNum, name: that.$t('k_出库') },
        { value: info.afterNum, name: that.$t('k_结余') },
      ]
      myChart2.setOption({
        title: {
          show: true,
          text: this.$t('库存数量占比'),
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          right: 30,
          top: 'center',
          icon: 'circle',
          data: [that.$t('k_入库'), that.$t('k_出库'), that.$t('k_结余')],
          formatter: function (name) {
            var target
            for (var i = 0, l = data.length; i < l; i++) {
              if (data[i].name == name) {
                target = data[i].value
              }
            }
            var arr = [name + '：' + target]
            return arr.join('\n')
          },
          type: 'scroll',
          pageIconColor: '#444',
          pageIconInactiveColor: '#eee',
        },
        series: [
          {
            name: this.$t('库存数量占比'),
            type: 'pie',
            radius: ['40%', '60%'],
            center: ['40%', '50%'],
            data: data,
            label: {
              normal: {
                show: true,
                position: 'inner',
                formatter: '{d}%',
              },
            },
          },
        ],
      })
    },
    dayAxios(list, arg0, arg) {
      let dayAxios = []
      list.forEach((lt) => {
        if (arg) {
          let day = new Date(lt[arg0]).getDay(),
            dayText = ''
          if (arg == 'week') {
            switch (day) {
              case 1:
                dayText = this.$t('周一')
                break
              case 2:
                dayText = this.$t('周二')
                break
              case 3:
                dayText = this.$t('周三')
                break
              case 4:
                dayText = this.$t('周四')
                break
              case 5:
                dayText = this.$t('周五')
                break
              case 6:
                dayText = this.$t('周六')
                break
              default:
                dayText = this.$t('周日')
                break
            }
            dayAxios.push(moment(new Date(lt[arg0])).format('MM-DD') + ' ' + dayText)
          }
          if (arg == 'month') {
            dayAxios.push(moment(new Date(lt[arg0])).format('yyyy-MM'))
          }
        } else {
          dayAxios.push(moment(new Date(lt[arg0])).format('MM-DD'))
        }
      })
      return dayAxios
    },
    dataBarOrLineAxios(list, arg, arg1) {
      let dataAxios = []
      list.forEach((lt) => {
        if (arg1 && arg1 == '1') {
          lt[arg] = Math.abs(lt[arg])
        }
        dataAxios.push(lt[arg])
      })
      return dataAxios
    },
    dataPieAxios(list, arg1, arg2) {
      let dataAxios = []
      list.forEach((lt) => {
        dataAxios.push({
          value: lt[arg1],
          name: lt[arg2],
        })
      })
      return dataAxios
    },
    min3(list, arg, arg1) {
      let min = Math.min.apply(
        Math,
        list.map((item) => {
          let num = 0
          if (arg) {
            num = arg1 && arg1 == '1' ? Math.abs(item[arg]) : item[arg]
          } else {
            num = arg1 && arg1 == '1' ? Math.abs(item) : item
          }
          return num
        })
      )
      min = Math.floor(min)
      return Number(min)
    },
  },
}
</script>

<style scoped>
.down-charts {
  padding: 0;
  margin: 0;
  box-shadow: none;
  background: white;
  border-radius: 15px;
  height: 22vw;
}
</style>